package com.jack.leetcode.string;

import java.util.HashMap;
import java.util.Map;

/***
 * @author zhangjie
 * @date 2020/3/24 21:34
 */
public class 无重复字符的最长子串 {

    public static void main(String[] args) {
        String s = "abcabdc";
        System.out.println(lengthOfLongestSubstring(s));
        s = "abcabcbb";
        System.out.println(lengthOfLongestSubstring(s));
        s = "bbbbb";
        System.out.println(lengthOfLongestSubstring(s));
        s = "pwwkew";
        System.out.println(lengthOfLongestSubstring(s));
    }

    public static int lengthOfLongestSubstring(String s) {
        if(s.length() == 0) return 0;
        Map<Character,Integer> map = new HashMap<>();
        int max = 0;
        int left = 0;
        for(int i=0;i<s.length();i++) {
            if(map.containsKey(s.charAt(i))){
                left = Math.max(left,map.get(s.charAt(i))+1);
            }
            map.put(s.charAt(i),i);
            max = Math.max(max,i-left+1);
        }
        return max;
    }
}
